﻿using Abp.Application.Services.Dto;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraLayout.Utils;
using HealthExamination.HardwareDrivers;
using HealthExamination.HardwareDrivers.Models.IdCardReader;
using Sw.His.Common.Functional.Unit.CustomTools;
using Sw.Hospital.HealthExaminationSystem.ApiProxy;
using Sw.Hospital.HealthExaminationSystem.ApiProxy.CusReg;
using Sw.Hospital.HealthExaminationSystem.Application.Charge.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.Common.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.Company;
using Sw.Hospital.HealthExaminationSystem.Application.Company.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.CusReg;
using Sw.Hospital.HealthExaminationSystem.Application.CusReg.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.IDNumber;
using Sw.Hospital.HealthExaminationSystem.Application.OccDisProposalNew;
using Sw.Hospital.HealthExaminationSystem.Application.OccHazardFactor.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.PersonnelCategorys;
using Sw.Hospital.HealthExaminationSystem.Common.Bases;
using Sw.Hospital.HealthExaminationSystem.Common.Enums;
using Sw.Hospital.HealthExaminationSystem.Common.GlobalSources;
using Sw.Hospital.HealthExaminationSystem.Common.Helpers;
using Sw.Hospital.HealthExaminationSystem.Common.Models;
using Sw.Hospital.HealthExaminationSystem.Common.UserCache;
using Sw.Hospital.HealthExaminationSystem.Comm;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using HealthExaminationSystem.Enumerations.Helpers;
using HealthExaminationSystem.Enumerations.Models;
using Sw.Hospital.HealthExaminationSystem.ApiProxy.Api.Controllers;
using DevExpress.Utils;
using Sw.Hospital.HealthExaminationSystem.Application.OccDisProposalNew.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.Market.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.Questionnaire.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.Questionnaire;
using Sw.Hospital.HealthExaminationSystem.ApiProxy.Questionnaire;
using Sw.Hospital.HealthExaminationSystem.Application.OccReview.Dto;
using Sw.Hospital.HealthExaminationSystem.Application.OccReview;
using Sw.Hospital.HealthExaminationSystem.ApiProxy.OccReview;

namespace Sw.Hospital.HealthExaminationSystem.CusReg
{
    public partial class CusRecords : UserBaseForm
    {
        #region 字典
        public List<SexModel> sexList;//性别字典
        public List<MarrySateModel> marrySateList;//婚育字典
        public List<BreedStateModel> breedStateList;//孕育字典
        public List<EnumModel> reviewStates;//复查状态字典
        public List<ClientRegDto> clientRegs;//单位及分组字典
        #endregion
        public string curCustomerBM;//当前体检号
        private ICustomerAppService customerSvr;//体检预约
        public bool isCustomerReg;//是否前台登记功能
        private IIDNumberAppService iIDNumberAppService;
        private IIdCardReaderHardwareDriver driver;
        // private readonly IFormRoleAppService _formRoleAppService;
        private IPersonnelCategoryAppService _personnelCategoryAppService;
        public List<ShowOccDictionary> showOccDictionarys;
        public readonly IOccDisProposalNewAppService _IOccDisProposalNewAppService = new OccDisProposalNewAppService();
        public string ArchNum;//当前档案号
        public string IDCardNum;//当前身份证号
                             
        private   IQuestionnaireAppService _questionnaireAppService;
        public   IOccReviewAppService _IOccReviewAppService;
        public CusRecords()
        {
            InitializeComponent();

        }
        public CusRecords(string _ArchNum, string _IDCardNum) : this()
        {
            ArchNum = _ArchNum;
            IDCardNum = _IDCardNum;

        }
        #region 事件
        private void CusDetail_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "体检档案";
                _IOccReviewAppService = new OccReviewAppService();
                _questionnaireAppService = new QuestionnaireAppService();
                //设置时间控件显示时间

                var clientlndutry = Enum.GetName(typeof(BasicDictionaryType), BasicDictionaryType.Clientlndutry);
                var Clientlndutry = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == clientlndutry).ToList();
                txtCustomerTrade.Properties.DataSource = Clientlndutry;
                _personnelCategoryAppService = new PersonnelCategoryAppService();

                this.KeyPreview = true;
                iIDNumberAppService = new IDNumberAppService();
                customerSvr = new CustomerAppService();
             
            
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                // tileView1.EndUpdate();
            }
        }      
        /// <summary>
        /// 加载记录
        /// </summary>
        private void getData()
        {
            #region 档案信息
            SearchCustomerDto searchCustomer = new SearchCustomerDto();
            searchCustomer.IDCardNo = IDCardNum;
            searchCustomer.ArchivesNum = ArchNum;
            var cuslist = customerSvr.getCusRecords(searchCustomer);
            if (cuslist != null && cuslist.Customerinfo != null)
            {
                #region 加载档案
                ReSetData(cuslist.Customerinfo);
                gridControl2.DataSource = cuslist.CusCheck;
                #endregion

            }
            #endregion
            //获取投诉记录
            #region 投诉记录
            var input = new QueryComplaintConditionInput();
            if (!string.IsNullOrEmpty(IDCardNum))
            {
                input.IdCard = IDCardNum;
            }
            else if (!string.IsNullOrEmpty(ArchNum))
            {
                input.ArchNum = ArchNum;
            }
            var result = DefinedCacheHelper.DefinedApiProxy.ComplaintAppService
                 .QueryComplaintInformationCollection(input).Result;
            gridControl投诉列表.DataSource = result;
            #endregion

            #region 问卷
            var inputwj = new QuestionnaireSearchInput();
            if (!string.IsNullOrEmpty(IDCardNum))
            {
                inputwj.IdCardNum = IDCardNum;
            }
            else if (!string.IsNullOrEmpty(ArchNum))
            {
                inputwj.ArchNum = ArchNum;
            }
            var resultwj = _questionnaireAppService.QueryQuestionnaireRecord(inputwj);
            gridControl1.DataSource = resultwj;

            #endregion
            #region 回访记录
            //回访信息
            CusVisitDto cusVisitDto = new CusVisitDto();
            cusVisitDto.remarks = ArchNum;
            var cusVisitManage = _IOccReviewAppService.SearchCusVisitManage(cusVisitDto);
            gridControlVisite.DataSource = cusVisitManage;
            #endregion

        }
      
        private void comSex_EditValueChanged(object sender, EventArgs e)
        {
         

        }
        /// <summary>
        /// 编辑控件中的按钮点击事件
        /// </summary>
        private void edior_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var editor = sender as PopupBaseEdit;
            if (e.Button.Kind == ButtonPredefines.Delete)
            {
                if (editor.EditValue == null)
                    return;
                editor.EditValue = null;

            }
        }
       
        /// <summary>
        /// 取消按钮
        /// </summary>
        private void butcancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
        #endregion


        #region 处理
        /// <summary>
        ///控件绑定数据源 赋值
        /// </summary>
        private void BindConrolData()
        {
            //字典无数据时加载数据
            if (sexList == null)
                sexList = SexHelper.GetSexForPerson();//.GetSexModelsForItemInfo();
            if (marrySateList == null)
                marrySateList = MarrySateHelper.GetMarrySateModels();
            if (breedStateList == null)
                breedStateList = BreedStateHelper.GetBreedStateModels();
            if (reviewStates == null)
                reviewStates = ReviewSateTypeHelper.GetReviewStates();
            if (clientRegs == null)
            {
                try
                {
                    //clientRegs = customerSvr.QuereyClientRegInfos(new FullClientRegDto());//加载单位分组数据
                }
                catch (UserFriendlyException ex)
                {
                    ShowMessageBox(ex);
                    return;
                }
            }

            
            txtPersonnelCategory.Properties.DataSource = _personnelCategoryAppService.QueryCategoryList(new Application.PersonnelCategorys.Dto.PersonnelCategoryViewDto()).Where(o => o.IsActive == true)?.ToList();
            comSex.Properties.DataSource = sexList;
            comMarriageStatus.Properties.DataSource = marrySateList;
            txtConceive.Properties.DataSource = breedStateList;
            lookUpEditCustomerType.Properties.DataSource = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.CustomerType.ToString())?.ToList();
          
            txtDegree.Properties.DataSource = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.DegreeType.ToString())?.ToList(); //CacheHelper.GetBasicDictionarys(BasicDictionaryType.DegreeType);
            txtSecretlevel.Properties.DataSource = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.SecrecyLevel.ToString())?.ToList();// CacheHelper.GetBasicDictionarys(BasicDictionaryType.SecrecyLevel);
            var emaillist = MessageEmailStateHelper.GetMessageEmailStates();
            emaillist.RemoveAll(o => o.Id == (int)MessageEmailState.HasBeenSent);
            txtEmailReport.Properties.DataSource = emaillist;
           // txtReportBySelf.Properties.DataSource = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.ReportSentType.ToString())?.ToList(); //CacheHelper.GetBasicDictionarys(BasicDictionaryType.ReportSentType);
            txtStoreAdressP.Properties.DataSource = AdministrativeDivisionHelper.GetProvince();//DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.Province.ToString())?.ToList();// CacheHelper.GetBasicDictionarys(BasicDictionaryType.Province);
            comStoreAdressS.Properties.DataSource = null;//DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.City.ToString())?.ToList(); //CacheHelper.GetBasicDictionarys(BasicDictionaryType.City);
            txtStoreAdressQ.Properties.DataSource = null;//DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.Area.ToString())?.ToList(); //CacheHelper.GetBasicDictionarys(BasicDictionaryType.Area);
            txtIDCardType.Properties.DataSource = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.CertificateType.ToString())?.ToList();// CacheHelper.GetBasicDictionarys(BasicDictionaryType.CertificateType);
            var shenfenzheng = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.CertificateType.ToString()).FirstOrDefault(o => o.Text.Contains("身份证"));// Common.Helpers.CacheHelper.GetBasicDictionarys(BasicDictionaryType.CertificateType).FirstOrDefault(o => o.Text == "身份证");
          
           
        }
       



        #endregion

        private void txtAge_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtAge.Text)) return;
            var year = DateTime.Now.Year - Convert.ToInt32(txtAge.EditValue);
            var date = new DateTime(year, DateBirthday.DateTime.Month, DateBirthday.DateTime.Day);
            if (date != DateBirthday.DateTime)
                DateBirthday.EditValue = date;
         
        }

        private void DateBirthday_Leave(object sender, EventArgs e)
        {
            if (DateBirthday.EditValue != null)
            {
                var age = DateTime.Now.Year - DateBirthday.DateTime.Year;
                if (txtAge.EditValue?.ToString() != age.ToString())
                    txtAge.EditValue = age;
            }
        }

        private void txtIDCardNo_ParseEditValue(object sender, ConvertEditValueEventArgs e)
        {

            if (txtIDCardType.Text.Contains("身份证"))
            {
                dxErrorProvider.ClearErrors();
                if (e.Value?.ToString() == null)
                {
                    txtAge.ReadOnly = false;
                    comSex.ReadOnly = false;
                    DateBirthday.ReadOnly = false;
                    return;
                }
                else
                {
                    var data = VerificationHelper.GetByIdCard(e.Value?.ToString());
                    if (data != null)
                    {
                        txtAge.EditValue = data.Age;
                        comSex.EditValue = (int)data.Sex;
                        DateBirthday.EditValue = data.Birthday;
                        txtAge.ReadOnly = true;
                        comSex.ReadOnly = true;
                        DateBirthday.ReadOnly = true;
                    }
                    else
                    {
                        dxErrorProvider.SetError(txtIDCardNo, string.Format("身份证号输入错误"));
                        txtIDCardNo.EditValue = null;
                        txtIDCardNo.Focus();
                        txtAge.ReadOnly = false;
                        comSex.ReadOnly = false;
                        DateBirthday.ReadOnly = false;
                    }
                }
            }
        }

        private void txtStoreAdressP_EditValueChanged(object sender, EventArgs e)
        {
            comStoreAdressS.EditValue = null;
            if (txtStoreAdressP.EditValue != null)
            {
                comStoreAdressS.Properties.DataSource =
                    AdministrativeDivisionHelper.GetCity(new AdministrativeDivisionDto
                    { Code = txtStoreAdressP.EditValue.ToString() });
            }
        }

        private void comStoreAdressS_EditValueChanged(object sender, EventArgs e)
        {
            txtStoreAdressQ.EditValue = null;
            if (comStoreAdressS.EditValue != null)
            {
                txtStoreAdressQ.Properties.DataSource =
                    AdministrativeDivisionHelper.GetCounty(new AdministrativeDivisionDto
                    { Code = comStoreAdressS.EditValue.ToString() });
            }
        }

        
        private void LoadData()
        {
            var closeWait = false;
            if (!splashScreenManager.IsSplashFormVisible)
            {
                splashScreenManager.ShowWaitForm();
                closeWait = true;
            }
            splashScreenManager.SetWaitFormDescription(Variables.LoadingForCloud);
            try
            {
                var result = customerSvr.getOneAddXQuestionnaires();
                splashScreenManager.SetWaitFormDescription(Variables.LoadingForForm);
                layoutControlGroupBase.BeginUpdate();
                foreach (var ques in result)
                {
                    if (ques.Category == "家族史")
                    {
                        var checkEdit = new CheckEdit
                        {
                            Text = ques.Name
                        };                   
                        checkEdit.Name = ques.Id.ToString("N");

                    }
                    if (ques.Category == "现病史")
                    {
                        var checkEdit = new CheckEdit
                        {
                            Text = ques.Name
                        };
                        
                        checkEdit.Name = ques.Id.ToString("N");
                    }

                    if (ques.Category == "现有症状或体征")
                    {
                        var checkEdit = new CheckEdit
                        {
                            Text = ques.Name
                        };
                        checkEdit.Width = 250;
                      
                        checkEdit.Name = ques.Id.ToString("N");

                    }

                }

                layoutControlGroupBase.EndUpdate();
            }
            catch (UserFriendlyException e)
            {
                ShowMessageBox(e);
            }
            finally
            {
                if (closeWait)
                {
                    if (splashScreenManager.IsSplashFormVisible)
                        splashScreenManager.CloseWaitForm();
                }
            }
        }      
      
      
        //重新加载控件数据
        public void ReSetData(QueryCustomerDto Customerinfo)
        {
            //txtCustoemrCode.EditValue = curCustomRegInfo.CustomerBM;
            txtArchivesNum.EditValue = Customerinfo.ArchivesNum;
            txtName.EditValue = Customerinfo.Name;
            comSex.EditValue = Customerinfo.Sex;
            txtAge.EditValue = Customerinfo.Age;
            comMarriageStatus.EditValue = Customerinfo.MarriageStatus;
            txtMobile.EditValue = Customerinfo.Mobile;
            txtIDCardNo.EditValue = Customerinfo.IDCardNo;
            txtIDCardType.EditValue = Customerinfo.IDCardType;
            DateBirthday.EditValue = Customerinfo.Birthday;
            if (Customerinfo.CustomerType.HasValue)
                lookUpEditCustomerType.EditValue = Customerinfo.CustomerType;
            else
            {
                lookUpEditCustomerType.EditValue = null;
                //lookUpEditCustomerType.EditValue = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.CustomerType.ToString())?.ToList().FirstOrDefault().Value;

            }
            //if (Customerinfo.PhysicalType.HasValue)
            //{
            //    lookUpEditClientType.EditValue = Convert.ToInt32(curCustomRegInfo.PhysicalType);
            //}
            //else
            //{
            //    lookUpEditClientType.EditValue = null;
            //    lookUpEditClientType.EditValue = DefinedCacheHelper.GetBasicDictionary().Where(o => o.Type == BasicDictionaryType.ExaminationType.ToString())?.ToList().FirstOrDefault().Value;
            //}
            //if (Customerinfo.PersonnelCategoryId.HasValue)
            //    txtPersonnelCategory.EditValue = Customerinfo.PersonnelCategoryId;

            txtTelephone.EditValue = Customerinfo.Telephone;
            
            txtWorkNumber.EditValue = Customerinfo.WorkNumber;
            ///txtCustomerTrade.EditValue = curCustomRegInfo.Customer.CustomerTrade;
            if (int.TryParse(Customerinfo.CustomerTrade, out int outrTrade))
            {
                txtCustomerTrade.EditValue = outrTrade;
            }
            txtDuty.EditValue = Customerinfo.Duty;
            txtDegree.EditValue = Customerinfo.Degree; 
            txtMedicalCard.EditValue = Customerinfo.MedicalCard;
            //txtSectionNum.EditValue = Customerinfo.SectionNum;
            txtVisitCard.EditValue = Customerinfo.VisitCard;
           // txtHospitalNum.EditValue = Customerinfo.HospitalNum;           
            txtSecretlevel.EditValue = Customerinfo.Secretlevel;
            txtGuoJi.EditValue = Customerinfo.GuoJi;           
            txtEmail.EditValue = Customerinfo.Email; 
            txtPostgCode.EditValue = Customerinfo.PostgCode;
            txtQq.EditValue = Customerinfo.Qq;
            if (!string.IsNullOrWhiteSpace(Customerinfo.StoreAdressP))
                txtStoreAdressP.EditValue = Customerinfo.StoreAdressP;
            if (!string.IsNullOrWhiteSpace(Customerinfo.StoreAdressS))
                comStoreAdressS.EditValue = Customerinfo.StoreAdressS;
            if (!string.IsNullOrWhiteSpace(Customerinfo.StoreAdressQ))
                txtStoreAdressQ.EditValue = Customerinfo.StoreAdressQ;
            txtAdress.EditValue = Customerinfo.Address;
            txthomeAdress.EditValue = Customerinfo.HomeAddress;
            txtRemarks1.EditValue = Customerinfo.Remarks;
             
        }

        private void gridLookUpEdit1View_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == colFree.FieldName)
            {
                var data = gridLookUpEdit1View.GetRowCellValue(e.ListSourceRowIndex, colIsFree);
                if (data != null)
                {
                    if ((bool)data)
                        e.DisplayText = "是";
                    else
                        e.DisplayText = "否";
                }
            }
        }

        private void comMarriageStatus_EditValueChanged(object sender, EventArgs e)
        {
        
        }

        private void txtConceive_EditValueChanged(object sender, EventArgs e)
        {
           
        }
  
        private void txtTypeWork_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var editor = sender as PopupBaseEdit;
            if (e.Button.Kind == ButtonPredefines.Delete)
            {
                if (editor.EditValue == null)
                    return;
                editor.EditValue = null;

            }
        }

        private void txtCheckType_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            var editor = sender as PopupBaseEdit;
            if (e.Button.Kind == ButtonPredefines.Delete)
            {
                if (editor.EditValue == null)
                    return;
                editor.EditValue = null;

            }
        }

        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (gridView2.GetFocusedRow() is QuestionnaireDto row)
            {
                var result = _questionnaireAppService.QueryQuestionBomRecordByQuestionnaireId(new EntityDto<Guid>(row.Id));
                var resultlist = result.Select(p=>p.bomItemName + ":" + p.answerContent).ToList();
                string strresult = string.Join("\r\n", resultlist);
                richEditWJ.Text = strresult;

                

            }
        }

        private void butOk_Click(object sender, EventArgs e)
        {

        }

        private void CusRecords_Shown(object sender, EventArgs e)
        {

            #region 加载表格下拉
            var complainWay = DefinedCacheHelper.GetBasicDictionarys(BasicDictionaryType.ComplainWay);
      
            var complainCategory = DefinedCacheHelper.GetBasicDictionarys(BasicDictionaryType.ComplainCategory);
  
            repositoryItemLookUpEditDj.DataSource = RegisterStateHelper.GetSelectList();
            repositoryItemLookUpEditdy.DataSource = PrintSateHelper.GetSexModels();
            repositoryItemLookUpEditzj.DataSource = SummSateHelper.GetSelectList();
            repositoryItemLookUpEdittj.DataSource = PhysicalEStateHelper.GetList();
            repositoryItemLookUpEdit投诉方式.DataSource = complainWay;
            repositoryItemLookUpEdit投诉类别.DataSource = complainCategory;
            repositoryItemLookUpEdit用户列表.DataSource = DefinedCacheHelper.GetComboUsers();
            repositoryItemLookUpEdit处理状态.DataSource = ComplaintProcessStateHelper.ComplaintProcessStateCollection;

            repositoryItemLookUpEdit紧急级别.DataSource = ComplaintExigencyLevelHelper.ComplaintExigencyLevelCollection;
            #endregion
            BindConrolData();
            //加载数据
            getData();
        }
    }
}
